﻿using System;
using System.Net;
using System.IO;

namespace IMeiWeiWebService
{
	public static class Util
	{
		public static HttpWebResponse MakeGetRequest(string requestUrl, string credentials)
		{
			try
			{
				HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;

				string authorization = String.Format ("Bearer {0}", credentials);
				request.Method = "Get";  
				request.Headers.Add("Authorization", authorization);

				HttpWebResponse response = request.GetResponse() as HttpWebResponse;
				
					if (response.StatusCode != HttpStatusCode.OK)
						throw new Exception(String.Format(
							"Server error (HTTP {0}: {1}).",
							response.StatusCode,
							response.StatusDescription));

					return response;

			}

			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				return null;
			}

		}

		public static HttpWebResponse MakePostRequest(string requestUrl, string jsonPostParam,string credentials)
		{
			try
			{
				HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;

				string authorization = String.Format ("Bearer {0}", credentials);
				request.Method = "Post";  
				request.Headers.Add("Authorization", authorization);

				request.ContentType = "application/json; charset=utf-8";
				request.Accept = "application/json";

				using (var streamWriter = new StreamWriter(request.GetRequestStream()))
				{

					streamWriter.Write(jsonPostParam);
					streamWriter.Flush();
					streamWriter.Close();

				HttpWebResponse response = request.GetResponse() as HttpWebResponse;

					if (response.StatusCode != HttpStatusCode.OK)
						throw new Exception(String.Format(
							"Server error (HTTP {0}: {1}).",
							response.StatusCode,
							response.StatusDescription));
					
				return response;
				}
			}

			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				return null;
			}

		}

		public static string GetJsonStringFromResponse(HttpWebResponse response){
		
			using (Stream s = response.GetResponseStream())
			{
				using (TextReader textReader = new StreamReader(s, true))
				{
					string jsonString = textReader.ReadToEnd();
					return jsonString;
				}
			}
		}
	}
}

